package Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Thread(ticket).start();
        new Thread(ticket).start();
        new Thread(ticket).start();
    }
}
class Ticket implements Runnable{

    int ticketNum=10;
    // 可重入锁
    private final ReentrantLock lock=new ReentrantLock();

    @Override
    public void run() {
        try {
            sell();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    private void sell() throws InterruptedException {
        try{
            // 加锁
            lock.lock();
            while(true){
                if(ticketNum<=0){
                    break;
                }
                Thread.sleep(1000);
                System.out.println(ticketNum--);
            }
        }finally {
            // 解锁
            lock.unlock();
        }
    }
}
